package com.derbysoft.dswitch.adapter.ihg.common.repository.impl;

import com.derbysoft.dswitch.adapter.ihg.common.domain.ConfigInfo;
import com.derbysoft.dswitch.adapter.ihg.common.repository.ConfigRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("configService")
public class ConfigRepositoryImpl extends CommonService<ConfigInfo> implements ConfigRepository {

    private static final String NAME = "name";
    private static final String USABLE = "usable";

    @Override
    public ConfigInfo loadByCode(String name) {
        return this.load("name",name);
    }

    @Override
    public ConfigInfo loadUsable(String name) {
        return load(new String[]{NAME, USABLE}, new Object[]{name, true});
    }

    @Override
    public void saveAll(List<ConfigInfo> configInfos) {
        for (ConfigInfo configInfo : configInfos) {
            ConfigInfo existConfigInfo = this.loadUsable(configInfo.getName());
            if (existConfigInfo != null) {
                existConfigInfo.setValue(configInfo.getValue());
                existConfigInfo.setUsable(configInfo.isUsable());
                existConfigInfo.setDescription(configInfo.getDescription());
            } else {
                existConfigInfo = new ConfigInfo();
                existConfigInfo.setName(configInfo.getName());
                existConfigInfo.setUsable(configInfo.isUsable());
                existConfigInfo.setDescription(configInfo.getDescription());
                existConfigInfo.setValue(configInfo.getValue());
            }
            this.commonDao.save(existConfigInfo);
        }
    }
}
